package com.example.shop_2207.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.shop_2207.entity.UserEntityResult
import com.example.shop_2207.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class LoginViewModel:BaseViewModel() {
    val loginSuccess = MutableLiveData<UserEntityResult>()//接收登录请求成功的结果
    val loginFail = MutableLiveData<String>()//接收登录请求失败的原因包括不限于 没网  项目中断等原因
    fun login(username:String,password:String){
        viewModelScope.launch {
            //手动添加trycatch方法，用来接收异常情况
            try {
                val map = mutableMapOf<String,String>()
                map.put("username",username)
                map["password"] = password //kotlin建议使用  和上面是一样的效果
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=UTF-8".toMediaType(),json)
                //执行请求
                val result= apiServer.login(body)
                //将请求结果进行保存
                loginSuccess.value = result
            }catch (e:Exception){
                //请求失败的情况
                loginFail.value = e.message
            }
        }
    }
}